package com.magicmovie.web.config;

import com.magicmovie.entity.User;
import com.magicmovie.web.service.UserRoleService;
import com.magicmovie.web.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 认证
 *
 * @author lee
 * @date 2018-01-16 14:00
 */
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    /**
     * 授权(验证权限时调用) 暂无权限管理
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String)principals.getPrimaryPrincipal();
        User user = userService.findByUserName(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if(user != null){
            List<String> roles = userRoleService.findByUser(user.getId());
            info.addRoles(roles);
        }
//        //用户权限列表
//        Set<String> permsSet = shiroService.getUserPermissions(userId);

//        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();

        //根据accessToken，查询用户信息
        User user = userService.findByUserName(username);

//        //token失效
//        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
//            throw new IncorrectCredentialsException("请重新登录");
//        }
//        账号锁定
        if(user == null ){
            throw new UnknownAccountException("账号不存在！");
        }
        if(user.getStatus().equals("01")){
            throw new LockedAccountException("账号已被禁用,请联系管理员");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),ByteSource.Util.bytes(user.getSalt()), getName());
        return info;
    }

}
